package com.ezjie.ielts.util;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ezjie.ielts.R;
import com.ezjie.ielts.module_read.adapter.SingleDialogAdapter;

public class AppUtil {
	private static Dialog progressDialog;
	private static Dialog noNetDialog;
	private static Dialog warnDialog;
	private static Dialog firstWarnDialog;

	/**
	 * 短时间显示Toast
	 * 
	 * @param info
	 *            显示的内容
	 */
	public static void showToast(Context context, String info) {
		Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param info
	 *            显示的内容
	 */
	public static void showToastLong(Context context, String info) {
		Toast.makeText(context, info, Toast.LENGTH_LONG).show();
	}

	/**
	 * 短时间显示Toast
	 * 
	 * @param info
	 *            显示的内容
	 */
	public static void showToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param info
	 *            显示的内容
	 */
	public static void showToastLong(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
	}

	/**
	 * 进度条对话框
	 */
	public static void showProgressDialog(Context context) {
		View view = LayoutInflater.from(context).inflate(R.layout.loading_layout, null);
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
		progressDialog = new Dialog(context, R.style.customDialog);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setContentView(view);
		progressDialog.show();
	}

	/**
	 * 隐藏正在加载的进度条
	 * 
	 */
	public static void dismissProgressDialog() {
		if (null != progressDialog && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public static void dismissWarnDialog() {
		if (null != warnDialog && warnDialog.isShowing()) {
			warnDialog.dismiss();
			warnDialog = null;
		}
	}

	public static void showOrHideInputManager(Context context, View v) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		// 隐藏软键盘
		// imm.hideSoftInputFromWindow(tv.getWindowToken(), 0);
		// 显示软键盘
		// imm.showSoftInputFromInputMethod(tv.getWindowToken(), 0);
		// 切换软键盘的显示与隐藏
		imm.toggleSoftInputFromWindow(v.getWindowToken(), 0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 验证用户名，支持中英文（包括全角字符）、数字、下划线和减号 （全角及汉字算两位）,长度为4-20位,中文按二位计数
	 * 
	 * @param userName
	 * @return
	 */
	public static boolean validateUserName(String userName) {
		String validateStr = "^[\\w\\-－＿[０-９]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]+$";
		boolean rs = false;
		rs = matcher(validateStr, userName);
		if (rs) {
			int strLenth = getStrLength(userName);
			if (strLenth < 6 || strLenth > 20) {
				rs = false;
			}
		}
		return rs;
	}

	/**
	 * 获取字符串的长度，对双字符（包括汉字）按两位计数
	 * 
	 * @param value
	 * @return
	 */
	public static int getStrLength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		for (int i = 0; i < value.length(); i++) {
			String temp = value.substring(i, i + 1);
			if (temp.matches(chinese)) {
				valueLength += 2;
			} else {
				valueLength += 1;
			}
		}
		return valueLength;
	}

	private static boolean matcher(String reg, String string) {
		boolean tem = false;
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(string);
		tem = matcher.matches();
		return tem;
	}

	public static boolean checkNickName(String nick) {
		if (TextUtils.isEmpty(nick))
			return false;
		if (nick.length() > 20 || nick.length() < 6)
			return false;
		return true;
	}

	public static boolean emailFormat(String email) {
		boolean tag = true;
		final String pattern1 = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	public static boolean usernameFormat(String username) {
		boolean tag = true;
		String pattern1 = "^(?!_)(?!.*?_$)[a-zA-Z\u4e00-\u9fa5]{1,10}+$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(username);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	/**
	 * 6-20位英文字符、下划线、数字组合
	 * 
	 * @param password
	 * @return
	 */
	public static boolean passwordFormat(String password) {
		boolean tag = true;
		String pattern1 = "^\\w{6,16}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(password);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	public static boolean zipCodeFormat(String password) {
		boolean tag = true;
		String pattern1 = "[1-9]\\d{5}(?!\\d)";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(password);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	public static boolean mobileFormat(String password) {
		boolean tag = true;
		String pattern1 = "^[1][3,5,7,8]+\\d{9}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(password);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	// 判断是否存在SIM卡
	public static boolean isExistsSIMCard(Context context) {
		TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (manager.getSimState() == TelephonyManager.SIM_STATE_READY)
			return true;
		return false;
	}

	// 拨打电话
	public static void callPhone(Context context, String phonenumber) {
		if (isExistsSIMCard(context)) {
			Intent intent = new Intent();
			intent.setAction("android.intent.action.CALL");
			intent.setData(Uri.parse("tel:" + phonenumber));
			LogUtils.d("exeucte here");
			context.startActivity(intent);
		} else {
			showToast(context, "请插入SIM卡");
		}

	}

	// 判断字符串不为空
	public static boolean isNotBlank(String str) {
		if (str != null && !"".equals(str) && !"null".equals(str))
			return true;
		return false;
	}

	// 中文编码
	public static String encoderBase64Str(String param) {
		if (isNotBlank(param)) {
			param = URLEncoder.encode(param);
			return param;
		}
		return "";
	}

	public interface onWarnDialogListener {
		public void onYesClick();
	}

	/**
	 * app中的对话框
	 * 
	 * @param context
	 * @param resId和msg都是内容
	 *            如果不能用resId就 resId传0
	 * @param isOneButton
	 */
	public static void showAppDialog(Context mContext, int contentResId, String msg, int yesResId, int noResId,
			int knowResId, boolean isOneButton, final OnDialogBtnClickImpl listener) {
		View view = LayoutInflater.from(mContext).inflate(R.layout.layout_app_dialog, null);

		final Dialog dialog = new Dialog(mContext, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		if (contentResId != 0) {
			tv_content.setText(contentResId);
		} else {
			tv_content.setText(msg);
		}

		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		if (isOneButton) {
			ll_layout1.setVisibility(View.GONE);
			ll_layout2.setVisibility(View.VISIBLE);
		} else {
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);
		}

		Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
		if (yesResId != 0) {
			btn_yes.setText(yesResId);
		}
		btn_yes.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();
				if (listener != null) {
					listener.onYesClick();
				}
			}
		});
		Button btn_no = (Button) view.findViewById(R.id.btn_no);
		if (noResId != 0) {
			btn_no.setText(noResId);
		}
		btn_no.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();
				if (listener != null) {
					listener.onNoClick();
				}
			}
		});
		Button btn_know = (Button) view.findViewById(R.id.btn_know);
		if (knowResId != 0) {
			btn_know.setText(knowResId);
		}
		btn_know.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();
				if (listener != null) {
					listener.onKnowClick();
				}
			}
		});
	}

	/**
	 * 普通对话框
	 * 
	 * @param context
	 * @param msg
	 * @param onWarnDialogListener
	 */
	public static void showWarnDialog(Context context, String msg, final onWarnDialogListener onWarnDialogListener) {
		new AlertDialog.Builder(context).setTitle(R.string.title).setMessage(msg)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						onWarnDialogListener.onYesClick();
					}

				}).show();

	}

	/**
	 * 普通对话框
	 * 
	 * @param context
	 * @param msg
	 * @param onWarnDialogListener
	 */
	public static void showWarnDialog2Button(Context context, String msg,
			final onWarnDialogListener onWarnDialogListener) {
		new AlertDialog.Builder(context).setTitle(R.string.title).setMessage(msg)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						onWarnDialogListener.onYesClick();
					}

				}).setNegativeButton(R.string.cancel, null).show();

	}

	/**
	 * 列表对话框
	 * 
	 * @param context
	 * @param items
	 * @param onClickListener
	 */
	public static KeyValuePair<AlertDialog, ListView> showSingleListDialog(Context context,
			ArrayList<KeyValuePair<String, Boolean>> list, final OnItemClickListener onItemClickListener) {
		final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		View dialogview = LayoutInflater.from(context).inflate(R.layout.layout_single_dialog, null);
		ListView listview = (ListView) dialogview.findViewById(R.id.lv_dialog_list);
		SingleDialogAdapter adapter = new SingleDialogAdapter(context, list);

		listview.setAdapter(adapter);
		listview.setOnItemClickListener(onItemClickListener);

		dialogview.findViewById(R.id.btn_dialog_cancel).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});

		alertDialog.show();
		alertDialog.getWindow().setContentView(dialogview);

		return new KeyValuePair<AlertDialog, ListView>(alertDialog, listview);
	}

	/**
	 * 内容为主对话框
	 * 
	 * @param context
	 * @param title
	 * @param content
	 */
	public static void showContentDialog(Context context, String title, String content) {
		final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		View dialogview = LayoutInflater.from(context).inflate(R.layout.layout_content_dialog, null);
		TextView titletv = (TextView) dialogview.findViewById(R.id.tv_dialog_title);
		TextView contenttv = (TextView) dialogview.findViewById(R.id.tv_dialog_content);

		titletv.setText(title);
		contenttv.setText(content);

		dialogview.findViewById(R.id.btn_dialog_cancel).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});

		alertDialog.show();
		alertDialog.getWindow().setContentView(dialogview);
	}

	/**
	 * 普通对话框 - 自定义布局
	 * 
	 * @param context
	 * @param msg
	 * @param onWarnDialogListener
	 */
	public static void showWarnDialog2Button(Context context, String msg, String yes, String no,
			final onWarnDialogListener onWarnDialogListener) {

		final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		View dialogview = LayoutInflater.from(context).inflate(R.layout.layout_read_back_dialog, null);
		TextView titletv = (TextView) dialogview.findViewById(R.id.tv_dialog_msg);
		Button btnno = (Button) dialogview.findViewById(R.id.btn_dialog_no);
		Button btnyes = (Button) dialogview.findViewById(R.id.btn_dialog_yes);

		titletv.setText(msg);
		btnno.setText(no);
		btnyes.setText(yes);

		btnyes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onWarnDialogListener.onYesClick();
			}
		});

		btnno.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});

		alertDialog.show();
		alertDialog.getWindow().setContentView(dialogview);
	}

	private static long lastClickTime;

	// 判断是否为快速点击， 筛词结束提交的时候要加判断
	public synchronized static boolean isFastClick() {
		long time = System.currentTimeMillis();
		if (time - lastClickTime < 500) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
}
